home *** CD-ROM | disk | FTP | other *** search
/ Nebula 1 / Nebula One.iso / Utilities / Unix / satan-1.1.1 / perl / get_host.pl < prev    next >
Text File  |  1995-04-10  |  2KB  |  81 lines

  1. require 'perl/socket.pl';
  2.  
  3. #  Lookup the FQDN for a host name or address with cacheing.
  4. #
  5. sub get_host_name {
  6.     local($host) = @_;
  7.     local($aliases, $type, $len, @ip, $a,$b,$c,$d);
  8.  
  9.     # do cache lookup first
  10.     if (exists($host_name_cache{$host})) {
  11.         return($host_name_cache{$host});
  12.         }
  13.  
  14.     # if host is ip address
  15.     if ($host =~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/) {
  16.         ($a,$b,$c,$d) = split(/\./, $host);
  17.         @ip = ($a,$b,$c,$d);
  18.         ($host) = gethostbyaddr(pack("C4", @ip), &AF_INET);
  19.         }
  20.     # if host is name, not ip address
  21.     else {
  22.         ($host, $aliases, $type, $len, @ip) = gethostbyname($host);
  23.         ($a,$b,$c,$d) = unpack('C4',$ip[0]);
  24.         }
  25.  
  26.     # success:
  27.     if ($host && @ip) {
  28.         $host =~ tr /A-Z/a-z/;
  29.         return $host_name_cache{$host} = $host;
  30.         }
  31.     # failure:
  32.     else {
  33.         return $host_name_cache{$host} = "";
  34.         }
  35.     }
  36.  
  37. #
  38. # Look up host address wich cacheing
  39. #
  40. sub get_host_addr {
  41.     local($host) = @_;
  42.     local($aliases, $type, $len, @ip, $a,$b,$c,$d);
  43.  
  44.     # do cache lookup first
  45.     if (exists($host_addr_cache{$host})) { 
  46.         return($host_addr_cache{$host}); 
  47.         }
  48.  
  49.     # if host is name, not ip address
  50.     if ($host =~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/) {
  51.         return $host;
  52.         } 
  53.     else {
  54.         ($host, $aliases, $type, $len, @ip) = gethostbyname($host);
  55.         ($a,$b,$c,$d) = unpack('C4',$ip[0]);
  56.         }
  57.  
  58.     # success; want IP address
  59.     if (@ip) { 
  60.         return "$a.$b.$c.$d";
  61.         }
  62.     # failure:
  63.     else { 
  64.         return $host_addr_cache{$host} = "";
  65.         }
  66.     }
  67.  
  68. #
  69. # Some scaffolding code for stand-alone testing.
  70. #
  71. if ($running_under_satan == 0) {
  72.     $running_under_satan = -1;
  73.  
  74.     warn "get_host.pl running in test mode";
  75.  
  76.     $host = &get_host_name($ARGV[0]); print "get_host_name: $host\n";
  77.     $host = &get_host_addr($ARGV[0]); print "get_host_addr: $host\n";
  78. }
  79.  
  80. 1;
  81.